package com.thinkgem.jeesite.modules.tb_message.webSocket;

import java.io.IOException;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.thinkgem.jeesite.common.utils.ToolsUtil;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.tb_message.service.WebSocketService;
/**
 * 
 * @author zhangYangZe
 *
 */
public class SystemWebSocketHandler implements WebSocketHandler {

	private static final Logger logger;
	private static final ArrayList<WebSocketSession> users;
	static{
		users = new ArrayList<WebSocketSession>();
		logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	}
	@Autowired
	private WebSocketService webSocketService;
	/**
	 * 关闭连接
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.debug("websocket connection closed......");
        users.remove(session);
	}

	/**
	 * 建立连接
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		// TODO Auto-generated method stub
		
		// TODO 连接成功
			try{
				logger.debug("connect to the websocket success......");
				users.add(session);
				
				 	System.out.println("afterConnectionEstablished");
			        System.out.println("getId:" + session.getId());
			        System.out.println("getLocalAddress:" + session.getLocalAddress().toString());
			        System.out.println("getTextMessageSizeLimit:" + session.getTextMessageSizeLimit());
			        System.out.println("getUri:" + session.getUri().toString());
			        System.out.println("getPrincipal:" + session.getPrincipal());
				
				String userName =(String) session.getAttributes().get(User.WEBSOCKET_USERNAME);
				if(ToolsUtil.isTrue(userName)){
					///int count = webSocketService.getUnReadNews(userName);
					session.sendMessage( new TextMessage("——————————提示弹窗——————————"));
				}
			}catch(Exception e){
				e.printStackTrace();
			}
				

	}
	/**
	 * 接受客户端发来消息
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		// TODO Auto-generated method stub

	}

	/**
	 * 当发生错误关闭
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		// TODO 关闭

		if(session.isOpen()){
			session.close();
		}
		logger.debug("websocket connection closed......");
        users.remove(session);
	}

	/**
	 * 是否分段发送消息
	 */
	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                	
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }  
    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public static void sendMsgToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                	
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get(User.WEBSOCKET_USERNAME).equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
	
    public static void sendMsgToUser(String userName, TextMessage message){
    	for (WebSocketSession user : users) {
            if (user.getAttributes().get(User.WEBSOCKET_USERNAME).equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    
}
